package com.ebelter.seneo.ui.activitys;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Window;
import android.view.WindowManager;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.utils.StatusBarUtil;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.log.LogUtils;


public abstract class SeneoBaseActivity extends FragmentActivity {
    public String TAG2 = "BaseActivity";

    public String From;
    private StationListener mStationListener;

    private static final String[] permissions = new String[]{
            Manifest.permission.BLUETOOTH,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.INTERNET,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.BLUETOOTH_ADMIN};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TAG2 = getClass().getSimpleName();

        if (getIntent()!=null){
            From = getIntent().getStringExtra("from");
        }


        requestWindowFeature(Window.FEATURE_NO_TITLE);//设置无标题
        if (isFullScreen()){//设置是否全屏
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN|WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(loadLayoutById());
        //当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
        StatusBarUtil.setRootViewFitsSystemWindows(this,false);

        //设置状态栏透明
        StatusBarUtil.setTranslucentStatus(this);

        //设置状态栏的字体颜色
        StatusBarUtil.setDarkStatusIcon(this,true);

        checkPermissions();
        initView();
        initData();

        if (isOpenNetStationListener()||isOpenTimeChangeListener()||isOpenBlueStationListener()){//只要有一个广播监听器打开就要开启广播
            mStationListener = new StationListener();
            //只要有一个监听器打开这个广播就要打开
            IntentFilter filter = new IntentFilter();
            if (isOpenNetStationListener()){//判断网络状态监听器是否需要打开
                filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            }

            if (isOpenTimeChangeListener()){//判断时间监听器是否需要打开
               // filter.addAction(Intent.ACTION_TIME_TICK);
                filter.addAction(Intent.ACTION_DATE_CHANGED);
            }

            if (isOpenBlueStationListener()){
                filter.addAction("android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED");
                filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
                filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
                filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
                filter.addAction("android.bluetooth.BluetoothAdapter.STATE_OFF");
                filter.addAction("android.bluetooth.BluetoothAdapter.STATE_ON");
            }

            registerReceiver(mStationListener, filter);
        }




    }

    public boolean isOpenTimeChangeListener() {
        return false;
    }


    //是否开启网络状态监听器
    protected boolean isOpenNetStationListener(){
        return false;
    }

    //是否开启蓝牙状态状态监听器
    protected boolean isOpenBlueStationListener(){
        return false;
    }

    private void checkPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (String p:permissions){
                // 首先是判断
                if (ContextCompat.checkSelfPermission(this, p) != PackageManager.PERMISSION_GRANTED) {
                    LogUtils.i(TAG2,"权限"+p+"没有授权成功1");
                    // Should we show an explanation?
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this, p)) {
                        // 显示弹框给用户的解释 采用系统的
                        LogUtils.i(TAG2,"权限"+p+"没有授权成功2--shouldShowRequestPermissionRationale");
                        ActivityCompat.requestPermissions(this, new String[]{p}, 1);
                    } else {
                        // No explanation needed, we can request the permission.
                        ActivityCompat.requestPermissions(this, new String[]{p}, 1);
                        LogUtils.i(TAG2,"权限"+p+"没有授权成功3--requestPermissions--"+p);
                    }
                }else {
                    LogUtils.i(TAG2,"权限"+p+"-----授权成功");
                }
            }
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);


        LogUtils.i2("SeneoBaseActivity","--------------------------------------------------");
        for (int i=0;i<permissions.length;i++){
            LogUtils.i2("SeneoBaseActivity","permissions["+i+"] = "+permissions[i]);
        }
        LogUtils.i2("SeneoBaseActivity","--------------------------------------------------");
        for (int i=0;i<permissions.length;i++){
            LogUtils.i2("SeneoBaseActivity","permissions["+i+"] = "+permissions[i]);
        }
        LogUtils.i2("SeneoBaseActivity","--------------------------------------------------");

        if (grantResults.length>0){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted 授予权限
                //处理授权之后逻辑
              //  ToastUtil.show("权限申请成功");
            } else {
                // Permission Denied 权限被拒绝
                ToastUtil.show("App permissions are prohibited. Please go to Settings -> Permissions Management to open the permissions, otherwise the app will not work properly!");
            }
        }




    }

    protected void initData() {
    }

    protected void initView() {
    }

    protected abstract int loadLayoutById() ;


    protected boolean isFullScreen(){
        return false;
    }


    //隐藏Fragment
    protected void hideAllFragment(FragmentTransaction transaction, Fragment... fragments) {
        if (transaction == null || fragments == null || fragments.length == 0) {
            return;
        }

        for (Fragment fragment : fragments) {
            if (fragment != null) transaction.hide(fragment);
        }
    }


    public void openActivity(Class<?> cls){
        Intent intent=new Intent(this,cls);
        startActivity(intent);
    }
    public void openActivity(String from,Class<?> cls){
        Intent intent=new Intent(this,cls);
        intent.putExtra("from",from);
        startActivity(intent);
    }


    private class StationListener extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent==null)return;
            String action = intent.getAction();
            if (TextUtils.isEmpty(action)){
                return;
            }

            //网络状态变化
            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
                int netWorkState = NetUtils.getNetWorkState(context);
                netStationChange(netWorkState);

            }else if (Intent.ACTION_TIME_TICK.equals(action)){//时间分钟变化
                timeChange(0);
            }else if (Intent.ACTION_DATE_CHANGED.equals(action)){//时间分钟变化
                timeChange(1);
            }

            bluetoothStationReceive(intent,action);

        }
    }


    /**

     public static final int NETWORK_NONE = -1;
     public static final int NETWORK_MOBILE = 0;
     public static final int NETWORK_WIFI = 1;
     */
    protected void netStationChange(int netWorkState){

    }


    /**
     * 0分钟变化 1日期变化
     */
    protected void timeChange(int which){

    }

    protected void bluetoothStationReceive(Intent intent,String action){

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        NetUtils.getInstance().cancelTag(this);
        if (isOpenNetStationListener()||isOpenTimeChangeListener()||isOpenBlueStationListener()){//反注册网络监听器
            if (mStationListener!=null)unregisterReceiver(mStationListener);
        }

    }
}
